package com.dyava.commons.lock;

import com.dyava.commons.valueplus.BooleanPlus;

import java.util.function.Supplier;

public abstract class KeyLockPool  {

    public abstract KeyLock createLock(String key);

    public boolean tryLock(String key, Runnable runnable){
        try(KeyLock lock = this.createLock(key)){
            boolean res = lock.tryLock();
            if(res){
                runnable.run();
                return true;
            }else{
                return false;
            }
        }
    }

    public <T> BooleanPlus<T> tryLock(String key, Supplier<T> supplier){
        try(KeyLock lock = this.createLock(key)){
            boolean res = lock.tryLock();
            if(res){
                T t = supplier.get();
                return BooleanPlus.of(true,t);
            }else{
                return BooleanPlus.of(false,null);
            }
        }
    }

    public void lock(String key,int maxWaitTime, Runnable runnable){
        try(KeyLock lock = this.createLock(key)){
            lock.lock(maxWaitTime);
            runnable.run();
        }
    }

    public <T> T lock(String key,int maxWaitTime, Supplier<T> supplier){
        try(KeyLock lock = this.createLock(key)){
            lock.lock(maxWaitTime);
            return supplier.get();
        }
    }


}
